package edu.tjut.tjutcommunity.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.tjut.tjutcommunity.entity.Academy;
import edu.tjut.tjutcommunity.mapper.AcademyMapper;
import edu.tjut.tjutcommunity.service.AcademyService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yhh
 * @since 2022-04-15
 */
@Service
public class AcademyServiceImpl extends ServiceImpl<AcademyMapper, Academy> implements AcademyService {

    final
    AcademyMapper academyMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public AcademyServiceImpl(AcademyMapper academyMapper) {
        this.academyMapper = academyMapper;
    }

    @Override
    public Integer getNo(String name) {
        QueryWrapper<Academy> qw = new QueryWrapper<>();
        qw.eq("name", name);
        Academy academy = academyMapper.selectOne(qw);
        if (academy == null) return 0;
        return academy.getAid();
    }

    @Override
    public List<Academy> getAcademies() {
        //获取redis，redis没有，获取mysql
        String academiesJson = stringRedisTemplate.opsForValue().get("academies");
        List<Academy> academies = JSON.parseArray(academiesJson, Academy.class);
        if(academies!=null) return academies;
        academies = academyMapper.selectList(null);
        stringRedisTemplate.opsForValue().set("academies",JSON.toJSONString(academies));
        return academies;
    }
}
